/**
 * Created by Ray on 2017/9/14.
 */
var AV = require('leanengine');
var common = require('../cloud/common');
var apis = require('../cloud/lib/apis');
var message = require('../cloud/lib/message');
var tribeHook = require('../cloud/tribeHook');
var async = require('async');
var moment = require("moment");
var TribeScore = AV.Object.extend('Tribe_score');
exports.tribeType = tribeType;

function tribeType(callback) {
    var query = new AV.Query('Dictionary');
    query.equalTo("type", '11');
    query.find().then(function (result) {
        var resultArr = [{name: '推荐', id: '0', pid: 'xz'}];
        var fatherObj = {name: "部落分类", id: "xz", expanded: true};
        resultArr.push(fatherObj);
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].get("code");
            temObj["name"] = result[i].get("name");
            temObj["pid"] = "xz";
            resultArr.push(temObj);
        }
        callback(resultArr)
    }, function (error) {
        console.log(error)
    })
}

exports.getTribe = getTribe;
function  getTribe(params) {
  let page = params.page
  let num = params.num
  let name = params.name
  let objectId = params.objectId
  let creater = params.creater
  let nickName = params.nickName
  let numNumber = params.numNumber

  if(page == '' || page ==undefined || page ==null){
    page = 0;
  }else{
    page = parseInt(page);
  }
  if(num ==''|| num==undefined || num ==null){
    num = 20
  }else{
    num = parseInt(num)
  }
  let query = new AV.Query('Tribe');
  if (name != "" && name != undefined && name != null) {
    query.contains("name", name);
  }
  if (creater != "" && creater != undefined && creater != null) {
    query.equalTo("creater", creater);
  }
  if (nickName != "" && nickName != undefined && nickName != null) {
    var innerQuery = new AV.Query('_User');
    innerQuery.contains('nickName', nickName);
    query.matchesQuery('createrObj', innerQuery);
  }
  if (objectId != "" && objectId != undefined && objectId != null) {
    query.equalTo("objectId", objectId);
  }
  if (numNumber != "" && numNumber != undefined && numNumber != null) {
    query.equalTo("num", Number(numNumber));
  }
    query.skip((page - 1)*num);
    query.limit(num);
    query.include('createrObj');
    query.equalTo('possibleChange','1') //可加分
    query.equalTo('status','1') //正常部落
    return query.find().then(function (result) {
       return  query.count().then(function (count) {
           if (result){
             let obj = {};
             let data = [];
             for(let item of result){
               let temObj = {};
               let createrObjVal = item.get("createrObj");
               temObj["creater"] = createrObjVal?createrObjVal.id:'';
               temObj["nickName"] = createrObjVal?createrObjVal.get("nickName"):'';
               temObj["gender"] = createrObjVal?(createrObjVal.get("userAvatar")?createrObjVal.get("userAvatar").url():''):'';
               temObj["objectId"] = item.get("objectId");
               temObj["name"] = item.get("name");
               temObj["possibleChange"] = item.get("possibleChange");
               temObj["maxNum"] = item.get("maxNum");
               temObj["createdAt"] =moment(item.get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
               data.push(temObj);
             }
             obj.data = data;
             obj.total = count;
             return obj;
           } else {
            console.log('没找到部落！')
           }
        }).catch(err=>{
         console.log(err)
       }).catch(error=>{
         console.log(error)
       })
    })
}
exports.getSelTribe = getSelTribe;
function getSelTribe(objectId) {
    let query = new AV.Query('Tribe');
    return query.get(objectId).then(function (result) {
        return result;
    }, function (error) {
        console.log(error);
    })
}

exports.updateTribePossible = updateTribePossible;
function  updateTribePossible(objectId,possibleBonus,maxNum) {
    let tribe = AV.Object.createWithoutData('Tribe',objectId);
    tribe.set('possibleChange',possibleBonus);
    tribe.set('maxNum',maxNum);
    return tribe.save().then(function (result) {
        return result;
    },function (error) {
        console.log(error)
    })
}
exports.tribeBonusAdd = tribeBonusAdd;
function  tribeBonusAdd(objectId) {
  let tribe = AV.Object.createWithoutData('Tribe',objectId);
  tribe.set('possibleChange','1');
  return tribe.save().then(function (result) {
    if (result){
      return result;
    }
    else {
        console.log('部落加分状态保存失败！')
    }
  },function (error) {
    console.log(error)
  })
}

exports.tribeBonusRemove = tribeBonusRemove;
function tribeBonusRemove(objectId, callback) {
  // console.log(req)
  var tribe = AV.Object.createWithoutData('Tribe', objectId);
  // 修改属性
  tribe.set('possibleChange', '0');
  // 保存到云端
  tribe.save().then(function (result) {
      if (result){
        callback(JSON.stringify(result));
      } else {
        console.log('部落加分状态修改失败！');
      }
    }, function (error) {
      console.log(error);
    }
  )
}

exports.tribeCategory = tribeCategory;
function tribeCategory(callback) {
    var query = new AV.Query('Dictionary');
    query.equalTo("type", '11');
    query.find().then(function (result) {
        var resultArr = [];
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].get("code");
            temObj["text"] = result[i].get("name");
            resultArr.push(temObj);
        }
        callback(resultArr)
    }, function (error) {
        console.log(error)
    })
}
exports.getRegTribeDefault = getRegTribeDefault
function getRegTribeDefault(page,num) {

    if(page == '' || page ==undefined || page ==null){
        page = 0;
    }else{
        page = parseInt(page);
    }
    if(num ==''|| num==undefined || num ==null){
        num = 20
    }else{
        num = parseInt(num)
    }
    let query = new AV.Query('Reg_tribe_default');
    query.skip((page-1)*num);
    query.limit(num);
    query.include('tribeObj');
    query.ascending('createdAt');
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            let obj = {};
            let data = [];
            for(let item of result){
                let temObj = {};
                let tribeObjVal = item.get("tribeObj");
                temObj["id"] = item.get("objectId");
                temObj["objectId"] = tribeObjVal ? tribeObjVal.get("objectId"):'';
                temObj["name"] =  tribeObjVal ? tribeObjVal.get("name"):'';
                temObj["tribeAvator"] = tribeObjVal ? tribeObjVal.get("tribeAvator").url():'';
                temObj["qrCode"] = tribeObjVal ? tribeObjVal.get("qrCode").url():'';
                temObj["createdAt"] =  moment(item.get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}

exports.regTribeRemove = regTribeRemove
function  regTribeRemove(objectId) {
    if(objectId !='' || objectId !=undefined || objectId !=null){
        console.log(objectId)
        var regTribe = AV.Object.createWithoutData('Reg_tribe_default', objectId);
        return regTribe.destroy().then(res=>{
            return res
        }).catch(error=>{
            console.log(error)
        })
    }


}
exports.getRegTribeFind = getRegTribeFind;
function getRegTribeFind(tribeId, tribeName, page, num) {
    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Tribe');

    if (tribeName != "" && tribeName != undefined && tribeName != null) {
        query.contains('name', tribeName);
    }
    if (tribeId != "" && tribeId != undefined && tribeId != null) {
        query.equalTo("objectId", tribeId);
    }
    query.skip(page * num);
    query.limit(num);
    query.ascending('createdAt');

    return query.find().then(function (result) {
        return query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {}
                temObj["name"] = item.get("name");
                temObj["objectId"] = item.get("objectId");
                temObj["tribeAvator"] = item.get("tribeAvator") ? item.get("tribeAvator").url() : "";//部落头像
                temObj["createdAt"] = moment(item.get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj
        })
    })
}

exports.getTribeFind = getTribeFind;
function getTribeFind(tribeId, tribeName, page, num) {

    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Tribe');

    if (tribeName != "" && tribeName != undefined && tribeName != null) {
        query.contains('name', tribeName);
    }
    if (tribeId != "" && tribeId != undefined && tribeId != null) {
        query.equalTo("objectId", tribeId);
    }
    query.skip(page * num);
    query.limit(num);
    query.ascending('createdAt');

    return query.find().then(function (result) {
        return query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {}
                temObj["name"] = item.get("name");
                temObj["objectId"] = item.get("objectId");
                temObj["tribeAvator"] = item.get("tribeAvator") ? item.get("tribeAvator").url() : "";//部落头像
                temObj["createdAt"] = moment(item.get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj
        })
    })


}
exports.findRegMember = findRegMember
function findRegMember(objectId) {
    let regTribeDefault = new AV.Query('Reg_tribe_default');
    if(objectId !=''||objectId !=null|| objectId !=undefined){
        regTribeDefault.equalTo("tribeOId", objectId);
    }
    regTribeDefault.include('tribeObj');
    return regTribeDefault.first().then(function (result) {
        return result;
    })
}

exports.findTribeMember = findTribeMember
function findTribeMember(objectId) {
    let tribeOIdQuery = new AV.Query('Tribe_recommend');
    tribeOIdQuery.equalTo("tribeOId", objectId);
    tribeOIdQuery.include('tribeObj');
    let obj = {}
    return tribeOIdQuery.first().then(function (result) {
        if (result) {
            obj.status = result.get('tribeObj').get("status")
        }
        obj.data = result;
        return obj
    })
}

exports.insertRegTribeDefault = insertRegTribeDefault;
function insertRegTribeDefault(objectId) {
    let TribeDefault = AV.Object.extend('Reg_tribe_default');
    let tribeDefault = new TribeDefault();
    let tribeQuery = AV.Object.createWithoutData('Tribe', objectId);
    tribeDefault.set('tribeOId', objectId);
    tribeDefault.set('tribeObj', tribeQuery);
    return tribeDefault.save().then(function (result) {
        return result;
    })


}

exports.insertTribeMember = insertTribeMember
async function insertTribeMember(req) {
    let objectId = req.body.objectId;
    let name = req.body.name || "";
    let statu = req.body.statu;
    let status = req.body.status;
    let tribeQuery = AV.Object.createWithoutData('Tribe', objectId);
    if (status == 1) {
        tribeQuery.set('status', status);
        return tribeQuery.save().then(function (data) {
            return data;
        });
    }
    function getMin() {
        let query = new AV.Query('Tribe_recommend');
        query.equalTo('statu', '1');
        query.include('tribeObj');
        query.exists('tribeObj.createrObj');
        return query.find().then(function (result) {
            let min = 1;
            for (item of result) {
                let sort = item.get("sort")
                sort < min ? min = sort : min;
            }
            return min;
        })
    }

    let minVal = await getMin();
    let statuVal = minVal - 1;
    let TribeMember = AV.Object.extend('Tribe_recommend');
    let tribeMember = new TribeMember();
    tribeMember.set('tribeOId', objectId);
    tribeMember.set('tribeObj', tribeQuery);
    tribeMember.set('statu', statu);
    tribeMember.set('tribeName', name);
    tribeMember.set('sort', statuVal)
    return tribeMember.save().then(function (result) {
        return result
    })
}

exports.getTribeInformationForCategory = getTribeInformationForCategory;
function getTribeInformationForCategory(objectId, name, creater, nickName, type, numNumber, page, num, callback) {
    if (type === '推荐') {
        getRecommendTribe(function (result) {
            callback("null", result);
            return;
        })
    } else {
        if (page == '' || page == undefined || page == null) {
            page = 0;
        } else {
            page = parseInt(page);
        }
        if (num == '' || num == undefined || num == null) {
            num = 20
        } else {
            num = parseInt(num)
        }
        var query = new AV.Query('Tribe');

        if (name != "" && name != undefined && name != null) {
            query.contains("name", name);
        }
        if (creater != "" && creater != undefined && creater != null) {
            query.equalTo("creater", creater);
        }
        if (nickName != "" && nickName != undefined && nickName != null) {
            var innerQuery = new AV.Query('_User');
            innerQuery.contains('nickName', nickName);
            query.matchesQuery('createrObj', innerQuery);
        }
        if (objectId != "" && objectId != undefined && objectId != null) {
            query.equalTo("objectId", objectId);
        }
        if (type != "" && type != undefined && type != null) {
            query.equalTo("category", type);
        }
        if (numNumber != "" && numNumber != undefined && numNumber != null) {
            query.equalTo("num", Number(numNumber));
        }
        // query.skip((page - 1) * num);
        query.skip(page * num);
        query.limit(num);
        query.include('createrObj');
        query.descending('sortDate');

        query.find().then(function (result) {
                query.count().then(function (count) {
                    var obj = {};
                    var data = [];
                    var num = 0;
                    for (var i = 0; i < result.length; i++) {
                        var temObj = {};
                        num++;
                        temObj["objectId"] = result[i].get("objectId");//部落ID
                        temObj["creater"] = result[i].get("creater");//创建人
                        if (result[i].get("createrObj") == undefined) {
                            temObj["nickName"] = "无创建者";
                        } else {
                            temObj["nickName"] = result[i].get("createrObj").get('nickName');//创建人对象
                        }
                        temObj["name"] = result[i].get("name");//部落名称
                        temObj["tribeAvator"] = result[i].get("tribeAvator") ? result[i].get("tribeAvator").url() : "";//部落头像
                        temObj["category"] = result[i].get("category");//分类
                        temObj["num"] = result[i].get("num");//部落号
                        // temObj["rule"]=result[i].get("rule");//部落公告
                        temObj["introduction"] = result[i].get("introduction");//部落公告
                        temObj["capacity"] = result[i].get("capacity");//部落规模
                        temObj["memberNum"] = result[i].get("memberNum");//成员数量
                        temObj["postNum"] = result[i].get("postNum");//帖子数量
                        temObj["qrCode"] = result[i].get("qrCode") ? result[i].get("qrCode").url() : "";//部落二维码
                        temObj["isPublic"] = result[i].get("isPublic");//公开非公开 默认全公开 1是公开 0 是私有
                        temObj["status"] = result[i].get("status"); //-1是删除，0是锁定，1是正常
                        temObj["verify"] = result[i].get("verify");//认证方式 1无需 2需要 3付费 4禁止加入
                        temObj["verifyCost"] = result[i].get("verifyCost");//付费部落金额
                        temObj["generalize"] = result[i].get("generalize");//推广分成0不开启1开启
                        // temObj["vipLevel"]=result[i].get("vipLevel");//VIP等级 默认为0
                        temObj["sortDate"] = result[i].get("sortDate");//排序日期（毫秒）
                        // temObj["sortTime"]=result[i].get("sortTime");//排序毫秒
                        // temObj["memberUIds"] = result[i].get("memberUIds");//部落成员
                        // temObj["createdAt"] = result[i].get("createdAt").toLocaleString();//创建时间
                        // temObj["updatedAt"] = result[i].get("updatedAt").toLocaleString();//更新时间
                        temObj["createdAt"] = moment(result[i].get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                        temObj["updatedAt"] = moment(result[i].get("updatedAt")).format('YYYY-MM-DD HH:mm:ss');
                        data.push(temObj);

                    }
                    obj.data = data;
                    obj.total = count;
                    callback("null", obj);
                })
            }, function (error) {
                console.log(error)
            }
        )
    }
}

function getRecommendTribe(callback) {

    var query = new AV.Query('Tribe_recommend');
    query.equalTo('statu', '1');
    query.include('tribeObj');
    query.include('tribeObj.createrObj');
    query.limit(40);
    query.ascending('sort');
    query.find().then(function (tribes) {
        if (tribes) {
            var returnArr = [];
            var count = tribes.length;
            for (var i = 0; i < count; i++) {
                var tribe = tribes[i].get('tribeObj');
                var returnObj = {};

                if (!tribe) {
                    continue;
                }

                returnObj["recommendOId"] = tribes[i].get('objectId');//部落推荐表objectId
                returnObj["objectId"] = tribe.get("objectId");//部落ID
                returnObj["creater"] = tribe.get("creater");//创建人ID
                returnObj["nickName"] = tribe.get("createrObj").get('nickName');//创建人
                returnObj["name"] = tribe.get("name");//部落名称
                returnObj["tribeAvator"] = tribe.get("tribeAvator") ? tribe.get("tribeAvator").url() : "";//部落头像
                returnObj["category"] = tribe.get("category");//分类
                returnObj["num"] = tribe.get("num");//部落号
                // returnObj["rule"]=tribe.get("rule");//部落公告
                returnObj["introduction"] = tribe.get("introduction");//部落公告
                returnObj["capacity"] = tribe.get("capacity");//部落规模
                returnObj["memberNum"] = tribe.get("memberNum");//成员数量
                returnObj["postNum"] = tribe.get("postNum");//帖子数量
                returnObj["qrCode"] = tribe.get("qrCode") ? tribe.get("qrCode").url() : "";//部落二维码
                returnObj["isPublic"] = tribe.get("isPublic");//公开非公开 默认全公开 1是公开 0 是私有
                returnObj["status"] = tribe.get("status"); //-1是删除，0是锁定，1是正常
                returnObj["verify"] = tribe.get("verify");//认证方式 1无需 2需要 3付费 4禁止加入
                returnObj["verifyCost"] = tribe.get("verifyCost");//付费部落金额
                returnObj["generalize"] = tribe.get("generalize");//推广分成0不开启1开启
                returnObj["vipLevel"] = tribe.get("vipLevel");//VIP等级 默认为0
                returnObj["sortDate"] = tribe.get("sortDate");//排序日期（毫秒）
                returnObj.sort = tribes[i].get('sort');//推荐排序
                // returnObj["sortTime"]=tribe.get("sortTime");//排序毫秒
                // returnObj["createdAt"] = tribe.get("createdAt").toLocaleString();//创建时间
                // returnObj["updatedAt"] = tribe.get("updatedAt").toLocaleString();//更新时间
                returnObj["createdAt"] = moment(tribe.get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                returnObj["updatedAt"] = moment(tribe.get("updatedAt")).format('YYYY-MM-DD HH:mm:ss');
                returnArr.push(returnObj);
            }
            return callback(returnArr);
        } else {
            return callback();
        }
    }).catch(function (reason) {
        console.log(reason)
    })
}
exports.removeTribe = removeTribe;
function removeTribe(objectId, callback) {
    // console.log(req)
    var tribe = AV.Object.createWithoutData('Tribe', objectId);
    // 修改属性
    tribe.set('status', '-1');
    // 保存到云端
    tribe.save().then(function (result) {
            console.log('部落删除完成');
            // console.log(JSON.stringify(result));
            callback(JSON.stringify(result));
        }, function (error) {
            console.log(error);
        }
    )
}
exports.recommendTribeRemove = recommendTribeRemove;
function recommendTribeRemove(objectId, callback) {
  let query = AV.Object.createWithoutData('Tribe_recommend',objectId);
  query.destroy().then(result=>{
    callback(result.id)
  }).catch(error=>{
    console.log('recommendTribeRemove：',error)
  })
}
exports.updateTribeInfo = updateTribeInfo;
function updateTribeInfo(req, callback) {
    var tribe = AV.Object.createWithoutData('Tribe', req.params.objectId);
    // 修改属性
    tribe.set('name', req.params.name);
    tribe.set('category', req.params.category);
    tribe.set('postNum', Number(req.params.postNum)); //Number类型
    tribe.set('capacity', Number(req.params.capacity)); //Number类型
    tribe.set('memberNum', Number(req.params.memberNum)); //Number类型
    tribe.set('isPublic', req.params.isPublic);
    tribe.set('status', req.params.status);
    tribe.set('verify', Number(req.params.verify)); //Number类型
    tribe.set('verifyCost', Number(req.params.verifyCost)); //Number类型
    tribe.set('generalize', Number(req.params.generalize)); //Number类型
    tribe.set('sortDate', Number(req.params.sortDate)); //Number类型
    tribe.set('introduction', req.params.introduction);

    // 保存到云端
    tribe.save().then(function (success) {
            callback("null", success);
        }, function (error) {
            console.log(error);
        }
    )
}
exports.checkTribeNameIsUsable = checkTribeNameIsUsable;
function checkTribeNameIsUsable(name, callback) {
    var rState = "0";
    if (name == null || name == "" || name == undefined) {
        return callback(rState);
    }
    var statusQuery = new AV.Query('Tribe');
    statusQuery.equalTo("name", name);
    var nameQuery = new AV.Query('Tribe');
    nameQuery.equalTo("status", "1");
    var query = AV.Query.and(statusQuery, nameQuery);
    query.first().then(function (tribeObj) {
        console.log('查询成功');
        if (tribeObj == null || tribeObj == undefined) {
            rState = "1";
        } else {
            rState = "0";
        }
        return callback(rState);
    }, function (error) {
        console.log(error);
        console.log('查询失败');
        return callback(error);
    })
}


//lzz
exports.updateThreadAudio = updateThreadAudio;

function updateThreadAudio(req) {

    let Media = AV.Object.extend('Media')
    let audio = new Media();
    return new Promise(function (resolve, reject) {
        audio.set("name", req.params.name);
        audio.set("type", req.params.type);
        audio.set("duration", req.params.duration);
        audio.save().then(function (data) {
            resolve(data)
        })

    }).then(function (data) {
        let threadObj = AV.Object.createWithoutData('Thread', req.params.objectId);
        threadObj.set('audioObj', data)
        threadObj.set('audioArray', [data])
        threadObj.set('streambackup', req.params.name)

        return threadObj.save().then(function (data) {
            console.log(data, "data====")
            return data
        })
    })
}

exports.updateThreadMedia = updateThreadMedia;
function updateThreadMedia(req) {
    let Media = AV.Object.extend('Media')
    let audio = new Media();
    return new Promise(function (resolve, reject) {
        audio.set("name", req.params.name);
        audio.set("type", req.params.type);
        audio.set("duration", req.params.duration);
        audio.save().then(function (data) {
            resolve(data)
        })

    }).then(function (data) {
        let threadObj = AV.Object.createWithoutData('Thread', req.params.objectId);
        threadObj.set('mediaObj', data)
        threadObj.set('mediaArray', [data])
        threadObj.set('streambackup', req.params.name)
        return threadObj.save().then(function (data) {
            return data
        })
    })
}


/**
 * 创建部落
 * request 中有以下参数
 *      name ：部落名称(必填参数)
 *        category :类别(必填参数)
 *        tribeAvator :部落头像(File的objectId)(可选参数)
 *        qrCode :部落二维码(File的objectId)(可选参数)
 *        introduction ：简介(可选参数)
 *        rule ：规定(可选参数)
 */
exports.createTribe = createTribe;
function createTribe(request, callback) {
    //console.log("createTribe:"+JSON.stringify(request.params));
    var name = request.params.name;
    var category = request.params.category;
    var capacity = request.params.capacity;
    var isPublic = request.params.isPublic;
    var status = request.params.status;
    var verify = request.params.verify;
    var verifyCost = request.params.verifyCost;
    var generalize = request.params.generalize;
    var introduction = request.params.introduction;
    var currentUid = request.user.id;
    var tribeAvator = request.params.tribeAvator;
    // console.log("========")
    // console.log(request)
    if (name == null || name == undefined) {
        name = "";
    }
    if (name == "") {
        return callback(JSON.stringify(common.getErrArr("错误的参数")));
    }
    name = name.replace(/\s+/g, "");
    if (category == null || category == undefined) {
        category = "";
    }
    if (isPublic == null || isPublic == undefined) {
        isPublic = "";
    }
    if (status == null || status == undefined) {
        status = "1";
    }
    if (generalize == null || generalize == undefined) {
        generalize = "";
    }
    if (introduction == null || introduction == undefined) {
        introduction = "";
    }
    var Tribe = AV.Object.extend("Tribe");
    var tribe = new Tribe();
    if (name != "") {
        tribe.set("name", name);
        tribe.set("nameArray", name.split(""));
    }
    if (category != "") {
        tribe.set("category", category);
    }
    tribe.set("capacity", Number(capacity));
    if (verify != "") {
        tribe.set("verify", Number(verify));
    }
    if (verifyCost != "") {
        tribe.set("verifyCost", Number(verifyCost));
    }
    if (isPublic != "") {
        tribe.set("isPublic", isPublic);
    }
    if (generalize != "") {
        tribe.set("generalize", Number(generalize));
    }
    if (introduction != "") {
        tribe.set("introduction", introduction);
    }
    if (tribeAvator != null && tribeAvator != undefined && tribeAvator != "") {
        tribe.set("tribeAvator", {"__type": "Pointer", className: "_File", objectId: tribeAvator});
    }
    // if (qrCode != null && qrCode != undefined && qrCode != "") {
    //   tribe.set("qrCode", {"__type": "Pointer", className: "_File", objectId: qrCode});
    // }
    // if (backgroundImage != null && backgroundImage != undefined && backgroundImage != "") {
    //   tribe.set("backgroundImage", {"__type": "Pointer", className: "_File", objectId: backgroundImage});
    // }
    var userObj = AV.Object.createWithoutData('_User', request.user.id);
    tribe.set("creater", request.user.id);
    tribe.set("createrObj", userObj);
    tribe.set("postNum", 0);
    tribe.set("memberNum", 1);
    tribe.set("activityNum", 0);
    tribe.set("status", status);
    tribe.set("sortDate", 100000000 + 1);
    tribe.set("sortTime", common.getCurrTime());
    tribe.set("memberUIds", [request.user.id]);
    // console.log(JSON.stringify(tribe))


    tribe.save().then(function (tribe) {
        // 成功
        // console.log("--------222 getTribeInfo-----")
        var TribeMember = common.getEntity("TribeMember");
        var tribeMember = new TribeMember();
        tribeMember.set("tribeOId", tribe.id);
        tribeMember.set("userOId", currentUid);
        tribeMember.set("userObj", userObj);
        tribeMember.set("tribeObj", tribe);
        tribeMember.set("userType", "1");
        tribeMember.set("sortNo", 1);
        tribeMember.set("sortNum", new Date().getTime() + 1000000);
        tribeMember.set("postNum", 0);
        tribeMember.set("handler", currentUid);
        tribeMember.set("changeTime", new Date().getTime());
        tribeMember.set("mySortNo", 1);
        tribeMember.set("isTop", 0);
        tribeMember.save();
        return callback(JSON.stringify("创建成功"));
    }, function (error) {
        // 失败
        // console.log("--------555 error------")
        console.log(error)
        return callback(JSON.stringify(common.getErrArr(error)));
    });
}

exports.tribeMGSortHandle = tribeMGSortHandle;
function tribeMGSortHandle(params, callback) {
    // console.log(params);
    var oldSort = parseInt(params.oldSort);
    var newSort = parseInt(params.tribeSort);
    var newSortIndex = parseInt(params.tribeSort) - 1;
    var tribeId = params.tribeId;
    var recommendOId = params.recommendOId;
    var query = new AV.Query('Tribe_recommend');
    query.equalTo('statu', '1');
    query.include('tribeObj');
    query.include('tribeObj.createrObj');
    query.limit(40);
    query.ascending('sort');
    query.find().then(function (tribes) {
        if (tribes) {
            var returnArr = [];
            // var dicArr = [];
            var count = tribes.length;
            for (var i = 0; i < count; i++) {
                returnArr.push(tribes[i].get('objectId'));
            }

            // console.log(JSON.stringify(returnArr));
            var oldSortIndex = returnArr.indexOf(recommendOId);
            // console.log(oldSortIndex);
            var newArr = [];
            if (newSortIndex > oldSortIndex) {
                console.log('排序下降');
                // console.log(dicArr);
                newArr = returnArr.slice(oldSortIndex, newSortIndex + 1);
                newArr.splice(0, 1);
                newArr.push(recommendOId);
                var objects = [];
                for (var j = 0; j < newArr.length; j++) {
                    //   var tempObj = {};
                    // tempObj["objectId"] = newArr[j];
                    // tempObj["sort"] = oldSort+j;
                    // tempArr.push(tempObj);

                    var tribeRecommendObj = AV.Object.createWithoutData('Tribe_recommend', newArr[j]);
                    tribeRecommendObj.set('sort', Number(oldSort + j));
                    objects.push(tribeRecommendObj);
                }
                ;
                AV.Object.saveAll(objects).then(function (objects) {
                    // 成功
                    // console.log(objects);
                    if (objects) {
                        return callback(JSON.stringify('排序成功！'));
                    } else {
                        return callback(JSON.stringify('排序失败！'));
                    }
                }, function (error) {
                    // 异常处理
                    console.log(error);
                    return callback(JSON.stringify(error));
                });
            } else if (newSortIndex < oldSortIndex) {
                console.log('排序提升');
                newArr = returnArr.slice(newSortIndex, oldSortIndex + 1);
                newArr.splice(newArr.length - 1, 1);
                newArr.splice(0, 0, recommendOId);
                var objects = [];
                for (var j = 0; j < newArr.length; j++) {
                    var tempObj = {};
                    // tempObj["objectId"] = newArr[j];
                    // tempObj["sort"] = newSort+j;
                    // tempArr.push(tempObj);

                    var tribeRecommendObj = AV.Object.createWithoutData('Tribe_recommend', newArr[j]);
                    tribeRecommendObj.set('sort', Number(newSort + j));
                    objects.push(tribeRecommendObj);
                }
                ;
                AV.Object.saveAll(objects).then(function (objects) {
                    // 成功
                    // console.log(objects);
                    if (objects) {
                        return callback(JSON.stringify('排序成功！'));
                    } else {
                        return callback(JSON.stringify('排序失败！'));
                    }
                }, function (error) {
                    // 异常处理
                    console.log(error);
                    return callback(JSON.stringify(error));
                });
            } else {
                return callback(JSON.stringify('没有符合的条件！'));
            }
            ;
        } else {
            return callback(JSON.stringify('没有找到这个部落！'));
        }
    }, function (error) {
        return callback(JSON.stringify(error));
    });
};

exports.getTribeMembers = getTribeMembers;
function getTribeMembers(params, callback) {
    var tribeOId = params.tribeOId;//部落标识
    var page = params.page;
    var num = params.num;
    var userOId = params.userOId;
    var userType = params.userType;
    var nickName = params.nickName;
    // console.log(params)

    var checkQueryTribeMember = new AV.Query('TribeMember');

    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    if (nickName != "" && nickName != undefined && nickName != null) {
        var innerQuery = new AV.Query('_User');
        innerQuery.contains('nickName', nickName);
        checkQueryTribeMember.matchesQuery('userObj', innerQuery);
    }
    if (userOId != "" && userOId != undefined && userOId != null) {
        checkQueryTribeMember.equalTo("userOId", userOId);
    }
    if (userType != "" && userType != undefined && userType != null && userType != -2) {
        checkQueryTribeMember.equalTo("userType", userType);
    }

    checkQueryTribeMember.equalTo("tribeOId", tribeOId);

    checkQueryTribeMember.skip(page * num);
    checkQueryTribeMember.limit(num);
    checkQueryTribeMember.descending('mySortNo');
    checkQueryTribeMember.include('userObj');
    checkQueryTribeMember.find().then(function (tribeMembers) {
        // console.log(tribeMembers);
        checkQueryTribeMember.count().then(function (count) {
            var data = [];
            var obj = {};
            for (var i = 0; i < tribeMembers.length; i++) {
                var userObj = {};
                num++;
                userObj["tirbeMemberId"] = tribeMembers[i].get("objectId");
                userObj["userType"] = tribeMembers[i].get("userType");
                userObj["userId"] = tribeMembers[i].get("userObj").get('objectId');
                userObj["userNickName"] = tribeMembers[i].get("userObj").get('nickName');
                userObj["userAvatar"] = tribeMembers[i].get("userObj").get("userAvatar") ? tribeMembers[i].get("userObj").get("userAvatar").url() : "";
                userObj["userQrCode"] = tribeMembers[i].get("userObj").get("qrCode") ? tribeMembers[i].get("userObj").get("qrCode").url() : "";
                data.push(userObj);
            }
            obj.data = data;
            obj.total = count;
            return callback(JSON.stringify(obj));
        }, function (error) {
            console.log(error);
        });
    }, function (error) {
        console.log(error);
    });
};
exports.checkTribeMember = checkTribeMember;
function checkTribeMember(params, callback) {
    var tribeOId = params.tribeOId;//部落标识
    var userOId = params.userOId;
    var checkQueryTribeMember = new AV.Query('TribeMember');
    if (userOId != "" && userOId != undefined && userOId != null) {
        checkQueryTribeMember.equalTo("userOId", userOId);
    }
    checkQueryTribeMember.equalTo("tribeOId", tribeOId);
    checkQueryTribeMember.include('userObj');
    checkQueryTribeMember.first().then(function (tribeMembers) {
        // console.log(JSON.stringify(tribeMembers));
        if (tribeMembers) {
            return callback(JSON.stringify(tribeMembers.get("userType")));
        } else {
            return callback(JSON.stringify('没有找到成员'));
        }

    }, function (error) {
        console.log(error);
    });
};

exports.addTribeMember = addTribeMember;
function addTribeMember(request, callback) {
//   var tribeOId = params.tribeOId;
//   var userOId = params.userOId;
//   var userType = params.userType;
//   var handler = params.handler;
    var user = AV.Object.createWithoutData('_User', request.userOId);
    request.user = user;
    var currentUid = request.user.id;
    var objectId = request.tribeOId;
    var userType = request.userType;
    var handler = request.handler;
    if (objectId == "" || objectId == null || objectId == undefined || request.user == null) {
        return callback(JSON.stringify("错误的参数"));
    }
    var query = new AV.Query('Tribe');
    query.equalTo("objectId", objectId);
    query.equalTo("status", apis['tribe']['status_normal']);
    query.first().then(function (object) {
        if (object != null) {
            var memberNum = object.get("memberNum");
            var capacity = object.get("capacity");
            if (memberNum >= capacity) {
                return callback(JSON.stringify("部落人员已满，请加入别的感兴趣的部落"));
            } else {
                message.addTribe(request.user.id, objectId, request.user.get("nickName"), function () {
                });

                var uIds = [];
                if (object.get("memberUIds") != null && object.get("memberUIds") != "" && object.get("memberUIds") != undefined)
                    uIds = object.get("memberUIds");
                uIds.push(currentUid);
                //去重
                uIds = common.arrayDistinctStr(uIds);
                object.set("memberUIds", uIds);
                object.fetchWhenSave(true);
                object.increment("memberNum");
                object.increment("sortDate");
                object.save();
                //更新置顶的部落排序 序号+1
                common.findTopTribeList(currentUid, function (error, tribeMemberList) {
                    if (error) {
                        return callback(JSON.stringify(error.message));
                    } else {
                        if (tribeMemberList.length > 0) {
                            var topTribeMemberList = [];
                            var generalMaxSortNo = 0;
                            tribeMemberList.forEach(function (tribe_member_info) {
                                if (tribe_member_info != null) {
                                    var mySortNo = tribe_member_info.get('mySortNo');
                                    if (mySortNo == null || mySortNo == '' || mySortNo == undefined)
                                        mySortNo = 1;

                                    if (generalMaxSortNo == 0)
                                        generalMaxSortNo = mySortNo;

                                    tribe_member_info.set('mySortNo', mySortNo + 1);
                                    topTribeMemberList.push(tribe_member_info);
                                }
                            });
                            AV.Object.saveAll(topTribeMemberList).then(function (list) {
                                if (error) {
                                    return callback(JSON.stringify(error.message));
                                }
                                if (generalMaxSortNo == 0)
                                    generalMaxSortNo = 1;
                                var TribeMember = common.getEntity("TribeMember");
                                var tribeMember = new TribeMember();
                                tribeMember.set("changeTime", new Date().getTime());
                                tribeMember.set("changeType", "1");
                                tribeMember.set("tribeOId", objectId);
                                tribeMember.set("userOId", currentUid);
                                tribeMember.set("userObj", request.user);
                                tribeMember.set("tribeObj", object);
                                tribeMember.set("sortNo", 3);
                                tribeMember.set("handler", handler);
                                tribeMember.set("userType", userType);
                                tribeMember.set("postNum", 0);
                                tribeMember.set("isTop", 0);
                                tribeMember.set("mySortNo", generalMaxSortNo);
                                tribeMember.save().then(function (tribeMemberInfo) {
                                    if (tribeMemberInfo) {
                                        return callback(JSON.stringify('添加成员成功！'));
                                    } else {
                                        return callback(JSON.stringify('部落成员表保存失败！'));
                                    }
                                    ;
                                }, function (error) {
                                    return callback(JSON.stringify(error));
                                });
                            }, function (error) {
                                return callback(JSON.stringify(error));
                            });

                        } else {
                            var TribeMember = common.getEntity("TribeMember");
                            var tribeMember = new TribeMember();
                            tribeMember.set("changeTime", new Date().getTime());
                            tribeMember.set("changeType", "1");
                            tribeMember.set("tribeOId", objectId);
                            tribeMember.set("userOId", currentUid);
                            tribeMember.set("userObj", request.user);
                            tribeMember.set("tribeObj", object);
                            tribeMember.set("sortNo", 3);
                            tribeMember.set("handler", handler);
                            tribeMember.set("userType", userType);
                            tribeMember.set("postNum", 0);
                            tribeMember.set("isTop", 0);
                            tribeMember.set("mySortNo", 0);
                            console.log('111');
                            tribeMember.save().then(function (tribeMemberInfo) {
                                if (tribeMemberInfo) {
                                    return callback(JSON.stringify('添加成员成功！'));
                                } else {
                                    return callback(JSON.stringify('部落成员表保存失败！'));
                                }
                                ;
                            }, function (error) {
                                return callback(JSON.stringify(error));
                            });
                        }
                    }

                });
            }
        } else {
            return callback(JSON.stringify("无效的信息，请刷新后重试"));
        }
    }, function (error) {
        return callback(JSON.stringify(error));
    });
};

// exports.addTribeMember = addTribeMember;
// function addTribeMember(params, callback) {
//   var tribeOId = params.tribeOId;
//   var userOId = params.userOId;
//   var userType = params.userType;
//   var handler = params.handler;
//   // console.log(params);
//   var tribeObj = AV.Object.createWithoutData('Tribe', tribeOId);
//   tribeObj.fetch().then(function (tribeInfo) {
//     var memberUIds = tribeInfo.get("memberUIds");
//     // console.log(memberUIds);
//     //如果要检索的字符串值没有出现，则该方法返回 -1
//     var isExist = memberUIds.indexOf(userOId);
//     if(isExist == -1){
//       // console.log('memberUIds不存在该用户');
//       tribeInfo.addUnique('memberUIds', userOId);
//       var capacity = tribeInfo.get("capacity");
//       var memberNum = tribeInfo.get("memberNum");
//       var number = parseInt(capacity) - parseInt(memberNum);
//       if ( number > 1 ){
//
//         //如果数组中不包含指定对象，将该对象加入数组，对象的插入位置是随机的。
//         tribeInfo.set('memberNum', Number(parseInt(memberNum)+1)); //Number类型
//         tribeObj.save().then(function (tribeObjSave) {
//           // // console.log(tribeObjSave);
//           console.log('tribeObjSave成功');
//           if(tribeObjSave){
//             var userObj = AV.Object.createWithoutData('_User', userOId);
//             message.addTribe(userOId, tribeOId, userObj.get("nickName"), function () {
//             });
//             var TribeMember = common.getEntity("TribeMember");
//             var tribeMember = new TribeMember();
//             tribeMember.set("changeTime", new Date().getTime());
//             tribeMember.set("changeType", "1");
//             tribeMember.set("tribeOId", tribeOId);
//             tribeMember.set("userOId", userOId);
//             tribeMember.set("userObj", userObj);
//             tribeMember.set("tribeObj", tribeObj);
//             tribeMember.set("userType", userType);
//             tribeMember.set("sortNo", 3);
//             tribeMember.set("sortNum", new Date().getTime() + 1000000);
//             tribeMember.set("postNum", 0);
//             tribeMember.set("handler", handler);
//             tribeMember.set("mySortNo", 1);
//             tribeMember.set("isTop", 0);
//             tribeMember.save().then(function (tribeMemberSave) {
//               // console.log(tribeMemberSave);
//               if(tribeMemberSave){
//                 console.log('tribeMemberSave成功');
//                 return callback(JSON.stringify('添加成员成功！'));
//               }
//             },function (error) {
//               return callback(JSON.stringify(error));
//             });
//           } else {
//             return callback(JSON.stringify('tribeObjSave失败'));
//           }
//         },function (error) {
//           return callback(JSON.stringify(error));
//         });
//       } else {
//         return callback(JSON.stringify('成员数量达到上限，无法添加新成员！'))
//       }
//     } else {
//       return callback(JSON.stringify('成员已经存在，请不要重复添加！'))
//     }
//
//   }, function (error) {
//     // 异常处理
//     console.log(error);
//     return callback(JSON.stringify(error))
//   });
// };

exports.tribeMemberEditHandle = tribeMemberEditHandle;
function tribeMemberEditHandle(params, callBack) {
    // console.log(params);
    var userId = params.userId;
    var tirbeMemberId = params.tirbeMemberId;
    var tribeOId = params.tribeOId;
    var newUserType = params.userType;
    var oldUserType = params.oldUserType;
    var handler = params.handler;

    var tribeObj = AV.Object.createWithoutData('Tribe', tribeOId);
    tribeObj.fetch().then(function (tribeInfo) {
        if (tribeInfo) {
            var blackUIds = [], memberUIds = [];
            // console.log(tribeInfo.get("memberUIds"));
            // console.log(tribeInfo.get("blackUIds"));
            if (tribeInfo.get("memberUIds") != "" && tribeInfo.get("memberUIds") != undefined) {
                memberUIds = tribeInfo.get("memberUIds");
            }
            if (tribeInfo.get("blackUIds") != "" && tribeInfo.get("blackUIds") != undefined) {
                blackUIds = tribeInfo.get("blackUIds");
            }
            var memberUIdsIndex = memberUIds.indexOf(userId);
            var blackUIdsIndex = blackUIds.indexOf(userId);

            if (newUserType == -1) {
                console.log('非成员');
                if (memberUIdsIndex != -1) {
                    memberUIds.splice(memberUIdsIndex, 1);
                }
                if (blackUIdsIndex != -1) {
                    blackUIds.splice(blackUIdsIndex, 1);
                }
            } else if (newUserType == 0) {
                console.log('黑名单');
                if (memberUIdsIndex != -1) {
                    memberUIds.splice(memberUIdsIndex, 1);
                }
                if (blackUIdsIndex == -1) {
                    blackUIds.push(userId);
                }
            } else if (newUserType == 2 || newUserType == 3) {
                if (blackUIdsIndex != -1) {
                    blackUIds.splice(blackUIdsIndex, 1);
                }
                if (memberUIdsIndex == -1) {
                    memberUIds.push(userId);
                }
            } else {
                return callBack(JSON.stringify('用户类型错误'));
            }
            tribeObj.set('memberUIds', memberUIds);
            tribeObj.set('blackUIds', blackUIds);
            tribeObj.set('memberNum', memberUIds.length);
            tribeObj.save().then(function (info) {
                if (info) {
                    var tribeMemberObj = AV.Object.createWithoutData('TribeMember', tirbeMemberId);
                    tribeMemberObj.set("userType", newUserType);
                    tribeMemberObj.set("handler", handler);
                    tribeMemberObj.set("changeTime", new Date().getTime());
                    if (newUserType == -1) {
                        tribeMemberObj.set("sortNo", 3);
                        tribeMemberObj.set("changeType", '0');
                    } else if (newUserType == 0) {
                        tribeMemberObj.set("sortNo", 4);
                        tribeMemberObj.set("changeType", '0');
                    } else if (newUserType == 1) {
                        tribeMemberObj.set("sortNo", 1);
                        tribeMemberObj.set("changeType", '1');
                    } else if (newUserType == 2) {
                        tribeMemberObj.set("sortNo", 2);
                        tribeMemberObj.set("changeType", '1');
                    } else if (newUserType == 3) {
                        tribeMemberObj.set("sortNo", 3);
                        tribeMemberObj.set("changeType", '1');
                    }
                    tribeMemberObj.save().then(function (tribeMember) {
                        // console.log(tribeMember);
                        if (tribeMember) {
                            return callBack(JSON.stringify('部落成员信息保存成功！'));
                        } else {
                            return callBack(JSON.stringify('部落成员信息表保存失败！'));
                        }
                        ;
                    }, function (error) {
                        // console.log(error);
                        if (error) {
                            return callBack(JSON.stringify(error));
                        }
                    })
                } else {
                    return callBack(JSON.stringify('部落成员信息保存成功！'));
                }
            }, function (error) {
                return callBack(JSON.stringify(error));
            });
        } else {
            return callBack(JSON.stringify('无法获取部落信息！'));
        }
    }, function (error) {
        // console.log(error);
        if (error) {
            return callBack(JSON.stringify(error));
        }
    });
};
exports.getThreadInfo = getThreadInfo;
function getThreadInfo(params, callBack) {
    // console.log(params);
    var page = params.page;
    var num = params.num;
    var objectId = params.objectId;
    var tribeOId = params.tribeOId;
    var tribeName = params.tribeName;
    var creater = params.creater;
    var nickName = params.nickName;
    var threadContent = params.threadContent;
    var status = params.status;
    if (status == '2') {
        status = '';
    }
    var queryThread = new AV.Query('Thread');

    if (objectId != "" && objectId != undefined && objectId != null) {
        queryThread.equalTo("objectId", objectId);
    }
    if (tribeOId != "" && tribeOId != undefined && tribeOId != null) {
        queryThread.equalTo("tribeOId", tribeOId);
    }
    if (tribeName != "" && tribeName != undefined && tribeName != null) {
        var innerQueryTribeName = new AV.Query('Tribe');
        innerQueryTribeName.contains('name', tribeName);
        queryThread.matchesQuery('tribeObj', innerQueryTribeName);
    }
    if (creater != "" && creater != undefined && creater != null) {
        queryThread.equalTo("creater", creater);
    }
    if (nickName != "" && nickName != undefined && nickName != null) {
        var innerQueryNickName = new AV.Query('_User');
        innerQueryNickName.contains('nickName', nickName);
        queryThread.matchesQuery('createrObj', innerQueryNickName);
    }
    if (threadContent != "" && threadContent != undefined && threadContent != null) {
      queryThread.contains("content", threadContent);
    }

    if (status != "" && status != undefined && status != null) {
        queryThread.equalTo("status", Number(status));
    }
    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }


    queryThread.skip(page * num);
    queryThread.limit(num);
    queryThread.include("createrObj");
    queryThread.include("tribeObj");
    // queryThread.include("fromCreaterObj");
    queryThread.include("picArray");
    queryThread.include("picArrayB");
    queryThread.include("audioObj");
    queryThread.include("mediaObj");
    // queryThread.include("audioArray");
    // queryThread.include("mediaArray");
    // queryThread.include("goods");
    // queryThread.include("fromThreadObj");
    // queryThread.descending('sortTime');
    queryThread.descending('createdAt');

    queryThread.find().then(function (result) {
        // console.log(JSON.stringify(result));
        if (!result) {
            return callBack(JSON.stringify('没有找到相关帖子！'));
        }
        ;
        queryThread.count().then(function (count) {

            var obj = {};
            var data = [];
            var num = 0;
            for (var i = 0; i < result.length; i++) {
                var temObj = {};
                num++;
                temObj["objectId"] = result[i].get("objectId");//帖子ID
                if (result[i].get("createrObj") == undefined) {
                    temObj["nickName"] = "无创建者";
                } else {
                    temObj["nickName"] = result[i].get("createrObj").get('nickName');//创建人对象
                }
                temObj["creater"] = result[i].get("creater");//创建人
                temObj["content"] = result[i].get("content");//内容
                temObj["tribeOId"] = result[i].get("tribeOId");
                if (result[i].get("tribeObj") == undefined) {
                    temObj["tribeName"] = "";
                } else {
                    temObj["tribeName"] = result[i].get("tribeObj").get('name');//部落名称
                }
                ;
                temObj["status"] = result[i].get("status");//状态 -1 删除 0关闭 1打开
                temObj["sortTime"] = result[i].get("sortTime");//排序时间
                temObj["isShare"] = result[i].get("isShare");//0不能分享 1可以分享
                temObj["postNum"] = result[i].get("postNum");//回复数量
                temObj["enjoyNum"] = result[i].get("enjoyNum");//赞数量
                temObj["isTiming"] = result[i].get("isTiming");//帖子是否是定时发送 0 不定时
                // temObj["createdAt"] = result[i].get("createdAt").toLocaleString()//创建时间
                // temObj["updatedAt"] = result[i].get("updatedAt").toLocaleString();//更新时间
                temObj["createdAt"] = moment(result[i].get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                temObj["updatedAt"] = moment(result[i].get("updatedAt")).format('YYYY-MM-DD HH:mm:ss');
                // console.log(moment(result[i].get("createdAt")).format('YYYY-MM-DD HH:mm:ss'));
                temObj["fromCreater"] = result[i].get("fromCreater");//原作者
                temObj["fromThread"] = result[i].get("fromThread");//来源帖
                temObj["fromTribe"] = result[i].get("fromTribe");//分享来源部落
                temObj["threadUrl"] = "http://health.aladada.com/tribeInfo?id=" + result[i].get("objectId") + "&uId=" + result[i].get("creater") + "&tId=" + result[i].get("tribeOId");
                temObj["surfacePic"] = result[i].get("surfacePic");//封面图
                temObj["picArray"] = result[i].get("picArray");//图片数组
                temObj["picArrayB"] = result[i].get("picArrayB");
                if (result[i].get("audioObj") == undefined) {
                    temObj["audioUrl"] = "";
                } else {
                    temObj["audioUrl"] = "http://tribemedia.aladada.com/" + result[i].get("audioObj").get('name');

                }
                ;
                if (result[i].get("mediaObj") == undefined) {
                    temObj["mediaUrl"] = "";
                } else {
                    temObj["mediaUrl"] = "http://tribemedia.aladada.com/" + result[i].get("mediaObj").get('name');
                }
                ;
                temObj["streamId"] = result[i].get("streamId");
                // if(result[i].get("streamId") == undefined){
                //   // temObj["audioStream"] = "";
                //   temObj["streamId"] = "";
                // } else {
                //   temObj["streamId"] = result[i].get("streamId");
                // var startTime = parseInt(result[i].get("startTime")/1000);
                // var endTime = Date.parse(new Date());
                // // var endTime = new Date().getTime();
                // temObj["audioStream"] = "http://10004zw.playback1.z1.pili.qiniucdn.com/buluoquan/"+result[i].get("streamId")+".m3u8?start="+startTime+"&end="+endTime;
                // }

                // temObj["audioUrl"] = result[i].get("audioObj");//音频对象
                // temObj["audioArray"] = result[i].get("audioArray");//语音数组
                // temObj["mediaObj"] = result[i].get("mediaObj");//视频对象
                // temObj["mediaArray"] = result[i].get("mediaArray");//视频数组
                // temObj["videoUrl"] = result[i].get("videoUrl");//语音url mp4格式
                // temObj["playTime"] = result[i].get("playTime");
                // temObj["startTime"] = result[i].get("startTime");
                // temObj["streambackup"] = result[i].get("streambackup");

                // temObj["isTop"] = result[i].get("isTop");//0正常 1置顶
                // temObj["shareContent"] = result[i].get("shareContent");//原帖内容
                // temObj["contentLower"] = result[i].get("contentLower");//帖子内容转小写
                // temObj["shareThreadStatus"] = result[i].get("shareThreadStatus");//分享原帖状态
                // temObj["tribeMemberObj"] = result[i].get("tribeMemberObj");//部落成员对象
                // temObj["editType"] = result[i].get("editType");
                // temObj["handler"] = result[i].get("handler");//操作人
                // temObj["shareNum"] = result[i].get("shareNum");
                // temObj["collectionNum"] = result[i].get("collectionNum");
                // temObj["goods"] = result[i].get("goods");
                // temObj["infocenterCount"] = result[i].get("infocenterCount");//动态数量
                // temObj["postCount"] = result[i].get("postCount");
                // temObj["enjoyCount"] = result[i].get("enjoyCount");
                // temObj["newPostCount"] = result[i].get("newPostCount");
                // temObj["newEnjoyCount"] = result[i].get("newEnjoyCount");//新的动态数量（点赞）
                // temObj["oldInfocenterCount"] = result[i].get("oldInfocenterCount");//变化前的动态数
                // temObj["fromThreadContent"] = result[i].get("fromThreadContent");//原帖内容
                // temObj["fromCreaterObj"] = result[i].get("fromCreaterObj");//原帖作者对象
                // temObj["fromThreadObj"] = result[i].get("fromThreadObj");//来源帖子对象
                // temObj["fromTribeObj"] = result[i].get("fromTribeObj");//来源部落对象
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callBack(JSON.stringify(obj));
        }, function (error) {
            callBack(JSON.stringify(error));
        });
    }, function (error) {
        callBack(JSON.stringify(error));
    });
};
exports.updateThreadInfo = updateThreadInfo;
function updateThreadInfo(params, callBack) {
    console.log(params);
    var objectId = params.objectId;
    var status = params.status;
    var isShare = params.isShare;
    var content = params.content;

    var thread = AV.Object.createWithoutData('Thread', objectId);
    // 修改属性
    thread.set('status', Number(status));
    thread.set('isShare', isShare);
    thread.set('content', content); //Number类型
    // 保存到云端
    thread.save().then(function (threadInfo) {
            if (threadInfo) {
                return callBack(JSON.stringify("帖子更新成功！"));
            } else {
                return callBack(JSON.stringify("帖子更新失败！"));
            }
        }, function (error) {
            console.log(error);
            return callBack(JSON.stringify(error));
        }
    )
}

exports.syncParentTribe = syncParentTribe;
async function syncParentTribe(name, relationTribeOId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('TribeLiveRelation_background');
    if (relationTribeOId != "" && relationTribeOId != undefined && relationTribeOId != null) {
        query.equalTo("relationTribeOId", relationTribeOId);
    }
    if (name != "" && name != undefined && name != null) {
        let tribeArr = await findTribes(name);
        query.containedIn("relationTribeOId", tribeArr)
    }
    query.limit(num);
    query.skip(num * page);
    query.equalTo("status", 1);
    query.include("relationTribeObj");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            var num = 0;
            for (var i = 0; i < result.length; i++) {
                var temObj = {};
                num++;
                temObj["objectId"] = result[i].get("relationTribeObj").get("objectId");//部落ID
                temObj["creater"] = result[i].get("relationTribeObj").get("creater");//创建人
                temObj["name"] = result[i].get("relationTribeObj").get("name");//部落名称
                temObj["tribeAvator"] = result[i].get("relationTribeObj").get("tribeAvator") ? result[i].get("relationTribeObj").get("tribeAvator").url() : "";//部落头像
                temObj["category"] = result[i].get("relationTribeObj").get("category");//分类
                temObj["num"] = result[i].get("relationTribeObj").get("num");//部落号
                // temObj["rule"]=result[i].get("rule");//部落公告
                temObj["introduction"] = result[i].get("relationTribeObj").get("introduction");//部落公告
                temObj["capacity"] = result[i].get("relationTribeObj").get("capacity");//部落规模
                temObj["memberNum"] = result[i].get("relationTribeObj").get("memberNum");//成员数量
                temObj["postNum"] = result[i].get("relationTribeObj").get("postNum");//帖子数量
                temObj["qrCode"] = result[i].get("relationTribeObj").get("qrCode") ? result[i].get("relationTribeObj").get("qrCode").url() : "";//部落二维码
                temObj["isPublic"] = result[i].get("relationTribeObj").get("isPublic");//公开非公开 默认全公开 1是公开 0 是私有
                temObj["status"] = result[i].get("status"); //-1是删除，0是锁定，1是正常
                temObj["verify"] = result[i].get("relationTribeObj").get("verify");//认证方式 1无需 2需要 3付费 4禁止加入
                temObj["verifyCost"] = result[i].get("relationTribeObj").get("verifyCost");//付费部落金额
                temObj["generalize"] = result[i].get("relationTribeObj").get("generalize");//推广分成0不开启1开启
                temObj["sortDate"] = result[i].get("relationTribeObj").get("sortDate");//排序日期（毫秒）
                temObj["createdAt"] = moment(result[i].get("relationTribeObj").get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                temObj["updatedAt"] = moment(result[i].get("relationTribeObj").get("updatedAt")).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);

            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    }, function (error) {
        console.log(error)
    })
}

exports.syncChildTribe = syncChildTribe;
async function syncChildTribe(parentRelationTribeOId, tribeOId, name, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('SynchronizationLiveTribe_background');
    if (tribeOId != "" && tribeOId != undefined && tribeOId != null) {
        query.equalTo("tribeOId", tribeOId);
    }
    if (parentRelationTribeOId != "" && parentRelationTribeOId != undefined && parentRelationTribeOId != null) {
        query.equalTo("parentRelationTribeOId", parentRelationTribeOId);
    }
    if (name != "" && name != undefined && name != null) {
        function findTribe(tribeName) {
            var TribeQuery = new AV.Query('Tribe');
            TribeQuery.limit(1000);
            TribeQuery.contains("name", tribeName);
            var findTribes = TribeQuery.find().then(function (result) {
                var tribeArr = [];
                for (let i = 0; i < result.length; i++) {
                    tribeArr.push(result[i].id);
                }
                return query.containedIn("tribeOId", tribeArr)
            });
            return findTribes;
        }

        await findTribe(name);
    }
    query.limit(num);
    query.skip(num * page);
    query.equalTo("status", 1);
    query.include("tribeObj");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            var num = 0;
            for (var i = 0; i < result.length; i++) {
                var temObj = {};
                num++;
                temObj["objectId"] = result[i].get("tribeObj").get("objectId");//部落ID
                temObj["creater"] = result[i].get("tribeObj").get("creater");//创建人
                temObj["name"] = result[i].get("tribeObj").get("name");//部落名称
                temObj["tribeAvator"] = result[i].get("tribeObj").get("tribeAvator") ? result[i].get("tribeObj").get("tribeAvator").url() : "";//部落头像
                temObj["category"] = result[i].get("tribeObj").get("category");//分类
                temObj["num"] = result[i].get("tribeObj").get("num");//部落号
                // temObj["rule"]=result[i].get("rule");//部落公告
                temObj["introduction"] = result[i].get("tribeObj").get("introduction");//部落公告
                temObj["capacity"] = result[i].get("tribeObj").get("capacity");//部落规模
                temObj["memberNum"] = result[i].get("tribeObj").get("memberNum");//成员数量
                temObj["postNum"] = result[i].get("tribeObj").get("postNum");//帖子数量
                temObj["qrCode"] = result[i].get("tribeObj").get("qrCode") ? result[i].get("tribeObj").get("qrCode").url() : "";//部落二维码
                temObj["isPublic"] = result[i].get("tribeObj").get("isPublic");//公开非公开 默认全公开 1是公开 0 是私有
                temObj["status"] = result[i].get("tribeObj").get("status"); //-1是删除，0是锁定，1是正常
                temObj["verify"] = result[i].get("tribeObj").get("verify");//认证方式 1无需 2需要 3付费 4禁止加入
                temObj["verifyCost"] = result[i].get("tribeObj").get("verifyCost");//付费部落金额
                temObj["generalize"] = result[i].get("tribeObj").get("generalize");//推广分成0不开启1开启
                temObj["sortDate"] = result[i].get("tribeObj").get("sortDate");//排序日期（毫秒）
                temObj["createdAt"] = moment(result[i].get("tribeObj").get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                temObj["updatedAt"] = moment(result[i].get("tribeObj").get("updatedAt")).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);

            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    }, function (error) {
        console.log(error)
    })
}

exports.deleteSyncTribe = deleteSyncTribe;
function deleteSyncTribe(tribeOId, parentRelationTribeOId, callback) {
    var query = new AV.Query('SynchronizationLiveTribe_background');
    query.equalTo("tribeOId", tribeOId);
    query.equalTo("parentRelationTribeOId", parentRelationTribeOId);
    query.find().then(function (todos) {
        todos.forEach(function (todo) {
            todo.set('status', 0);
        });
        AV.Object.saveAll(todos).then(function (result) {
            callback(null, result)
        }, function (error) {
            callback(error, null)
        })
    })
}

exports.notSyncChildTribe = notSyncChildTribe;
async function notSyncChildTribe(parentRelationTribeOId, tribeOId, name, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Tribe');
    if (parentRelationTribeOId != "" && parentRelationTribeOId != undefined && parentRelationTribeOId != null) {
        function findTribe(tribeOId, time, tribeSet) {
            var relationQuery = new AV.Query('SynchronizationLiveTribe_background');
            relationQuery.equalTo('parentRelationTribeOId', tribeOId);
            relationQuery.limit(1000);
            relationQuery.equalTo("status", 1);
            relationQuery.ascending("createdAt");
            if (time != "" && time != undefined && time != null) {
                relationQuery.greaterThan("createdAt", time);
            }
            return relationQuery.find().then(function (result) {
                var lastTime = result[result.length - 1].createdAt;
                if (result.length < 1000) {
                    for (let i = 0; i < result.length; i++) {
                        tribeSet.add(result[i].get("tribeOId"));
                    }
                    var tribeArr = Array.from(tribeSet);
                    // return query.notContainedIn("objectId",tribeArr);
                    return tribeArr;
                } else {
                    for (let i = 0; i < result.length; i++) {
                        tribeSet.add(result[i].get("tribeOId"));
                    }
                    findTribe(tribeOId, lastTime, tribeSet);
                }
                ;
            }, function (reject) {
                return reject
            }).catch(function (error) {
                callback(error, null);
            });
        }

        var relationSet = new Set();
        var lastArr = await findTribe(parentRelationTribeOId, "", relationSet);
        query.notContainedIn("objectId", lastArr);
    }
    if (tribeOId != "" && tribeOId != undefined && tribeOId != null) {
        query.equalTo("objectId", tribeOId);
    }
    if (name != "" && name != undefined && name != null) {
        query.contains("name", name);
    }
    query.limit(num);
    query.skip(num * page);
    query.ascending("createdAt");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            var num = 0;
            for (var i = 0; i < result.length; i++) {
                var temObj = {};
                num++;
                temObj["objectId"] = result[i].get("objectId");//部落ID
                temObj["creater"] = result[i].get("creater");//创建人
                temObj["name"] = result[i].get("name");//部落名称
                temObj["tribeAvator"] = result[i].get("tribeAvator") ? result[i].get("tribeAvator").url() : "";//部落头像
                temObj["category"] = result[i].get("category");//分类
                temObj["num"] = result[i].get("num");//部落号
                // temObj["rule"]=result[i].get("rule");//部落公告
                temObj["introduction"] = result[i].get("introduction");//部落公告
                temObj["capacity"] = result[i].get("capacity");//部落规模
                temObj["memberNum"] = result[i].get("memberNum");//成员数量
                temObj["postNum"] = result[i].get("postNum");//帖子数量
                temObj["qrCode"] = result[i].get("qrCode") ? result[i].get("qrCode").url() : "";//部落二维码
                temObj["isPublic"] = result[i].get("isPublic");//公开非公开 默认全公开 1是公开 0 是私有
                temObj["status"] = result[i].get("status"); //-1是删除，0是锁定，1是正常
                temObj["verify"] = result[i].get("verify");//认证方式 1无需 2需要 3付费 4禁止加入
                temObj["verifyCost"] = result[i].get("verifyCost");//付费部落金额
                temObj["generalize"] = result[i].get("generalize");//推广分成0不开启1开启
                temObj["sortDate"] = result[i].get("sortDate");//排序日期（毫秒）
                temObj["createdAt"] = moment(result[i].get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                temObj["updatedAt"] = moment(result[i].get("updatedAt")).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    }, function (error) {
        console.log(error)
    })
}

exports.addSynchronzationTribe = addSynchronzationTribe;
function addSynchronzationTribe(parentRelationTribeOId, tribeOId, callback) {
    var syncTribe = new AV.Query('SynchronizationLiveTribe_background');
    syncTribe.equalTo('tribeOId', tribeOId);
    syncTribe.first().then(function (objects) {
        if (objects != "" && objects != undefined) {
            if (objects.get("status") == 0) {
                objects.set("status", 1).save().then((result) => {
                        callback(null, "10001")
                    }, (error) => {
                        callback(error, "10003")
                    }
                )
            } else {
                callback(null, "10002");
            }
        } else {
            var RelationTribe = AV.Object.extend("SynchronizationLiveTribe_background");
            var relationTribe = new RelationTribe;
            var parentRelationTribeObj = AV.Object.createWithoutData("Tribe", parentRelationTribeOId);
            var tribeObj = AV.Object.createWithoutData("Tribe", tribeOId);
            relationTribe.set("parentRelationTribeObj", parentRelationTribeObj);
            relationTribe.set("parentRelationTribeOId", parentRelationTribeOId);
            relationTribe.set("tribeOId", tribeOId);
            relationTribe.set("tribeObj", tribeObj);
            relationTribe.save().then(function (result) {
                callback(null, "10001")
            })
        }
        // return response.success({success:'成功'});
    }, function (error) {
        console.log(error);
        callback(error, "10003")
    })

}

function findTribes(name) {
    let User = new AV.Query('Tribe');
    User.contains('name', name);
    User.limit(1000);
    return User.find().then(function (resullt) {
        var idArr = [];
        for (let i = 0; i < resullt.length; i++) {
            idArr.push(resullt[i].id);
        }
        return idArr;
    }, function (reject) {
        console.log(reject);
        return reject
    });
}

exports.tribeShareList = tribeShareList;
async function tribeShareList(objectId, userOId, nickName, tribeName, tribeOId, status, content, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Tribe_share_goods');
    if (tribeOId != "" && tribeOId != undefined && tribeOId != null) {
        query.equalTo("tribeOId", tribeOId);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    if (userOId != "" && userOId != undefined && userOId != null) {
        query.equalTo("userOId", userOId);
    }
    if (nickName != "" && nickName != undefined && nickName != null) {
        let Users = await findUser(nickName);
        query.containedIn("userOId", Users);
    }
    if (tribeName != "" && tribeName != undefined && tribeName != null) {
        let tribeArr = await findTribes(tribeName);
        query.containedIn("tribeOId", tribeArr)
    }
    if (tribeOId != "" && tribeOId != undefined && tribeOId != null) {
        query.equalTo("tribeOId", tribeOId);
    }
    if (status != "" && status != undefined && status != null) {
        query.equalTo("status", status);
    }
    if (content != "" && content != undefined && content != null) {
        query.contains("content", content);
    }
    query.limit(num);
    query.skip(num * page);
    query.include("tribeGoodsArray");
    query.include("associatedGroupArray");
    query.include("tribeObj");
    query.include("userObj");
    query.descending("createdAt");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (var i = 0; i < result.length; i++) {
                let temObj = {};
                let tribeGoodsOIds = [];
                let fightGoodsOIds = [];
                temObj["tribeOId"] = result[i].get("tribeOId");//部落ID
                temObj["isCanShare"] = result[i].get("isCanShare");//能否分享
                temObj["picName"] = result[i].get("picName") ? apis['qiniu']['url'] + "/" + result[i].get("picName") : '';//封面图
                if (result[i].get("tribeGoodsArray") != null && result[i].get("tribeGoodsArray") != undefined) {
                    for (let j = 0; j < result[i].get("tribeGoodsArray").length; j++) {
                        if (result[i].get("tribeGoodsArray")[j] != null) {
                            tribeGoodsOIds.push(result[i].get("tribeGoodsArray")[j].get("goodOId"))
                        }
                        ;
                    }
                }
                if (result[i].get("associatedGroupArray") != null && result[i].get("associatedGroupArray") != undefined) {
                    for (let j = 0; j < result[i].get("associatedGroupArray").length; j++) {
                        if (result[i].get("associatedGroupArray")[j] != null) {
                            fightGoodsOIds.push(result[i].get("associatedGroupArray")[j].get("goodsOId"));
                        }
                    }
                }
                temObj["tribeGoodsOIds"] = tribeGoodsOIds;
                temObj["fightGoodsOIds"] = fightGoodsOIds;
                temObj["objectId"] = result[i].id;
                temObj["content"] = result[i].get("content");//内容
                temObj["isTop"] = result[i].get("isTop");//没注释
                temObj["title"] = result[i].get("title");//标题
                temObj["enjoyNum"] = result[i].get("enjoyNum");//点赞数
                temObj["hotNum"] = result[i].get("hotNum");//浏览数
                temObj["tribeName"] = result[i].get("tribeObj") ? result[i].get("tribeObj").get("name") : "";//部落名称
                temObj["status"] = result[i].get("status");//状态0删除
                temObj["userName"] = result[i].get("userObj") ? result[i].get("userObj").get("nickName") : "";//创建用户
                temObj["userOId"] = result[i].get("userOId");
                temObj["createdAt"] = moment(result[i].get("createdAt")).format('YYYY年MM月DD HH:mm:ss');
                temObj["updatedAt"] = moment(result[i].get("updatedAt")).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);

            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    }, function (error) {
        console.log(error)
        callback(error, null)
    })
}
function findUser(userName) {
    var User = new AV.Query('_User');
    User.limit(1000);
    User.contains("nickName", userName);
    return User.find().then((result) => {
        let userArr = [];
        for (let item of result) {
            userArr.push(item.id);
        }
        return userArr;
    }, (reject) => {
        console.log(reject);
        return reject;
    })
}


exports.updateTribeUserType = updateTribeUserType;
function updateTribeUserType(objectId, userType, callback) {
    let Tribe = AV.Object.createWithoutData("TribeMember", objectId);
    Tribe.set("userType", userType);
    Tribe.save().then((result) => {
        callback(null, "10001")
    }, (error) => {
        console.log(error);
        callback(error, "10002")
    })
}

exports.updateTribeShare = updateTribeShare;
async function updateTribeShare(objectIds, callback) {
    let Tribe = new AV.Query('Tribe_share_goods');
    Tribe.containedIn("objectId", objectIds);
    Tribe.find().then(Tribes => {
        Tribes.forEach(todo => {
            todo.set("status", "0");
        })
        AV.Object.saveAll(Tribes).then(resolve => {
            callback(null, "10001")
        }, reject => {
            console.log(reject);
            callback(reject, "10002")
        })
    })
}
//删除帖子
// exports.updateTribeThread = updateTribeThread;
// async function updateTribeThread(objectIds, callback) {
//     let Tribe = new AV.Query('Thread');
//     Tribe.containedIn("objectId", objectIds);
//     Tribe.find().then(Tribes => {
//         Tribes.forEach(todo => {
//             todo.set("status", -1);
//         })
//         AV.Object.saveAll(Tribes).then(resolve => {
//             callback(null, "10001")
//         }, reject => {
//             console.log(reject);
//             callback(reject, "10002")
//         })
//     })
// }
exports.updateTribeThread = updateTribeThread;
async function updateTribeThread(objectIds) {
  let thread = new AV.Query('Thread');
  let score = -30
  thread.containedIn("objectId", objectIds);
  thread.equalTo('status',1)
   await thread.find().then(async threads => {
    let data = []
     await async.eachSeries(threads, function (item, cb) {
      item.set('status', -1)
      data.push(item)
      let tribeOId = item.get('tribeOId')
      let tribeObj = item.get("tribeObj")
      let scoreType = 'DEL_THREAD'
      let threadOId = item.id
      let type = '创建无效帖子'
      let createrObj = item.get('createrObj')
      createrObj.increment('score', score)
      createrObj.save().then(user => {
        let tribe_score = new TribeScore()
        tribe_score.set('tribeOId', tribeOId)
        tribe_score.set('scoreType', scoreType)
        tribe_score.set('threadObj', item)
        tribe_score.set('type', type)
        tribe_score.set('tribeObj', tribeObj)
        tribe_score.set('userObj', user)
        tribe_score.set('score', score)
        tribe_score.set('userOId', user.id)
        tribe_score.set('threadOId', threadOId)
        tribe_score.save().catch(errs => {
          console.log('errs',errs)
          cb(null)
        })
        cb(null)
      }).catch(err => {
        console.log('err',err)
        cb(null)
      })
    }, function (error) {
      console.log('error',error)
      if (data.length > 0) {
         AV.Object.saveAll(data).then(saveAllRes => {
          // console.log(saveAllRes)
        })
      }
    })
  }).catch(findErr=>{
    console.log('findErr',findErr)
  })
}

exports.deleteIneffectiveness = deleteIneffectiveness;
async function deleteIneffectiveness(page=0, callback) {
  console.log('开始删除无效帖子！')
  let templateList = await getTemplateList()
  let score = -30
  let query = new AV.Query('Thread');
  query.equalTo('status',1)
  query.doesNotExist('fromThreadObj')
  query.containedIn('content',templateList)
  query.doesNotExist('picArray')
  query.doesNotExist('surfacePic')
  query.doesNotExist('mediaObj')
  query.doesNotExist('streamId')

  query.include("tribeObj")
  query.include("createrObj")
  query.skip(page*1000)
  query.limit(1000)
  query.ascending("createdAt");
  query.find().then(threads=>{
    console.log(threads.length)

    let data = []
    async.eachSeries(threads, function (item, cb) {
      item.set('status',-1)
      data.push(item)
      let tribeOId = item.get('tribeOId')
      let tribeObj = item.get("tribeObj")
      let scoreType = 'DEL_THREAD'
      let threadOId = item.id
      let type =  '创建无效帖子'

      let createrObj = item.get('createrObj')
      createrObj.increment('score',score)
      createrObj.save().then(user=>{
        let tribe_score = new TribeScore()
        tribe_score.set('tribeOId',tribeOId)
        tribe_score.set('scoreType',scoreType)
        tribe_score.set('threadObj',item)
        tribe_score.set('type',type)
        tribe_score.set('tribeObj',tribeObj)
        tribe_score.set('userObj',user)
        tribe_score.set('score',score)
        tribe_score.set('userOId',user.id)
        tribe_score.set('threadOId',threadOId)
        tribe_score.save().catch(errs=>{
          console.log(errs)
          cb()
        })
        cb()
      }).catch(err=>{
        console.log(err)
        cb()
      })
    },function (error) {
      console.log(error)

      if (data.length>0){
        AV.Object.saveAll(data).then(ress=>{
          console.log("删除无效帖子，一波结束，共计删除：",data.length)
          if (data.length==1000) {
            deleteIneffectiveness(page++)
          }
        })
      }
    });

  }).catch(error=>{
    console.log(error)
  })

}
async function getTemplateList(){
  let query = new AV.Query('template_For_Thread');
  return query.find().then(result=>{
      let data = []
      for (let item of result){
        let content = item.get('content')
        data.push(content)
      }
      return data
  }).catch(error=>{
    console.log(error)
  })

}
exports.userTribeList = userTribeList;
async function userTribeList(userOId, nickName, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('TribeMember');
    if (userOId != "" && userOId != undefined && userOId != null) {
        query.equalTo("userOId", userOId);
    }
    if (nickName != "" && nickName != undefined && nickName != null) {
        let Users = await findUser(nickName);
        query.equalTo("userOId", Users[0]);
    }
    query.limit(num);
    query.skip(num * page);
    query.include("tribeObj");
    query.descending("createdAt");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (var i = 0; i < result.length; i++) {

                var temObj = {};
                temObj["objectId"] = result[i].get("tribeObj").get("objectId");//部落ID
                temObj["creater"] = result[i].get("tribeObj").get("creater");//创建人
                temObj["name"] = result[i].get("tribeObj").get("name");//部落名称
                temObj["tribeAvator"] = result[i].get("tribeObj").get("tribeAvator") ? result[i].get("tribeObj").get("tribeAvator").url() : "";//部落头像
                temObj["category"] = result[i].get("tribeObj").get("category");//分类
                // temObj["rule"]=result[i].get("rule");//部落公告
                temObj["introduction"] = result[i].get("tribeObj").get("introduction");//部落公告
                temObj["capacity"] = result[i].get("tribeObj").get("capacity");//部落规模
                temObj["memberNum"] = result[i].get("tribeObj").get("memberNum");//成员数量
                temObj["postNum"] = result[i].get("tribeObj").get("postNum");//帖子数量
                temObj["qrCode"] = result[i].get("tribeObj").get("qrCode") ? result[i].get("tribeObj").get("qrCode").url() : "";//部落二维码
                temObj["isPublic"] = result[i].get("tribeObj").get("isPublic");//公开非公开 默认全公开 1是公开 0 是私有
                temObj["status"] = result[i].get("tribeObj").get("status"); //-1是删除，0是锁定，1是正常
                temObj["verify"] = result[i].get("tribeObj").get("verify");//认证方式 1无需 2需要 3付费 4禁止加入
                temObj["verifyCost"] = result[i].get("tribeObj").get("verifyCost");//付费部落金额
                temObj["generalize"] = result[i].get("tribeObj").get("generalize");//推广分成0不开启1开启
                temObj["sortDate"] = result[i].get("tribeObj").get("sortDate");//排序日期（毫秒）
                temObj["createdAt"] = moment(result[i].get("createdAt")).format('YYYY年MM月DD HH:mm:ss');
                temObj["updatedAt"] = moment(result[i].get("updatedAt")).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    }, function (error) {
        console.log(error)
        callback(error, null)
    })
}